import axios from 'axios'
import {
    Message,
    MessageBox
} from 'element-ui'
import {
    removeAuth
} from '@/utils/auth'
import qs from 'qs'
import { debounce } from 'throttle-debounce'
import router from '../router'
import Lockr from 'lockr'
import store from '@/store/index.js'
/**
 * 检查dom是否忽略
 * @param {*} e
 */
const clearCacheEnterLogin = debounce(500, () => {
    removeAuth().then(() => {
        location.reload() // 为了重新实例化vue-router对象 避免bug
    }).catch(() => {
        location.reload()
    })

})

const errorMessage = debounce(500, (message, type = 'error') => {
    Message({
        message: message,
        duration: 1500,
        type: type
    })
})

const confirmMessage = debounce(1000, (message) => {
    MessageBox.confirm(message, '提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
    }).then(() => {
        clearCacheEnterLogin()
    }).catch(() => { })
})

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

// const apiUrl= window.location.protocol+'//'+ (process.env.NODE_ENV === 'production' ? window.location.host + '/' : process.env.VUE_APP_BASE_API);
const apiUrl = process.env.VUE_APP_REQUSET_API;

window.BASE_URL = apiUrl;
const service = axios.create({
    baseURL: apiUrl, // api 的 base_url
    timeout: 60000 // 请求超时时间
})
// request拦截器
service.interceptors.request.use(
    config => {

        let Authorization = Lockr.get('logintoken') || '';
        if (Authorization) {
            config.headers['token'] = Authorization;
        }
        let localLang = localStorage.getItem('language');
        config.headers['Accept-Language'] = localLang == 'en' ? 'en' : 'cn';

        const flag = config.headers['Content-Type'] && config.headers['Content-Type'].indexOf('application/json') !== -1
        if (!flag) {
            // const mult = config.headers['Content-Type'] && config.headers['Content-Type'].indexOf('multipart/form-data') !== -1


            config.data = config.data
            // if (mult) {
            //     config.data = config.data
            // } else {
            //     config.data = qs.stringify(config.data)
            // }
        } else {
            if (config.data === undefined || config.data === null) {
                // 不传参的情况下 json类型的提交数据，校准为 空对象
                config.data = {}
            }
        }
        return config
    },
    error => {
        // Do something with request error
        return Promise.reject(error)
    }
)

// response 拦截器
service.interceptors.response.use(
    response => {
        const res = response.data;
        const code = res.code,
            msg = res.msg;
        if (code == 0 && msg) {
            errorMessage(msg)
            return new Promise(() => { })
        } else {
            return res.data
        }
    },
    async (error) => {
        if (error.response) {
            const response = error.response;

            if (response.status == 401) {
                errorMessage('账号已过期，请重新登录', 'warning')
                await new Promise(resolve => setTimeout(resolve, 1500))
                store.dispatch('LogOut').then(() => {
                    localStorage.clear()
                    router.push({ path: "/login" });
                });
            }
        }
    }
)

export default service